package org.datastealer.filter;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.datastealer.filter.wrapper.DateStealerRequestWrapper;
import org.datastealer.properties.DataStealerProperties;
import org.datastealer.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Note：记录查询发生的url和参数
 *
 * @author ：mengjw
 * @description：DataStealer日志拦截器
 * @date ：Created in 2020/9/13
 */
@Slf4j
@Component
public class DataStealerLogFilter implements Filter {

    @Autowired
    private DataStealerProperties dataStealerProperties;

    /**
     * 注册拦截器
     *
     * @param dataStealerLogFilter
     * @return
     */
    @Bean("dataStealerLogFilterRegistration")
    public FilterRegistrationBean registerFilter(DataStealerLogFilter dataStealerLogFilter) {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(dataStealerLogFilter);
        registrationBean.addUrlPatterns("/datastealer/*");
        registrationBean.setOrder(1);
        registrationBean.setAsyncSupported(true);
        return registrationBean;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (dataStealerProperties.logQuery && request instanceof RequestFacade) {
            log.info("调用DataStealer接口:{}", ((RequestFacade) request).getServletPath());
            if (!request.getParameterMap().isEmpty()) {
                log.info("接口参数：{}", JsonUtils.getObjectMapper().writeValueAsString(request.getParameterMap()));
            }
            DateStealerRequestWrapper requestWrapper = new DateStealerRequestWrapper((HttpServletRequest) request);
            String requestBody = requestWrapper.getBody();
            if (!StringUtils.isEmpty(requestBody)) {
                log.info("包体内容：{}", requestBody);
            }
            chain.doFilter(requestWrapper, response);
        } else {
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {
    }

}